<template>
  <div class="student-list-demo">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span class="title">学生管理演示</span>
          <div class="header-actions">
            <el-button type="primary" @click="addMockData">
              <el-icon><Plus /></el-icon>
              添加模拟数据
            </el-button>
            <el-button @click="clearData">
              <el-icon><Delete /></el-icon>
              清空数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索筛选 -->
      <div class="search-form">
        <div class="search-form-header">
          <h3 class="search-title">
            <el-icon><Search /></el-icon>
            筛选条件
          </h3>
          <div class="search-stats">
            <span class="result-count">共 {{ filteredStudentList.length }} 条结果</span>
            <el-button 
              text 
              type="primary" 
              @click="toggleSearchForm"
              class="toggle-btn"
            >
              {{ searchFormCollapsed ? '展开' : '收起' }}
              <el-icon class="toggle-icon" :class="{ 'is-collapsed': searchFormCollapsed }">
                <ArrowDown />
              </el-icon>
            </el-button>
          </div>
        </div>
        
        <el-collapse-transition>
          <div v-show="!searchFormCollapsed" class="search-form-content">
            <el-form :model="searchForm" class="search-form-inner">
              <el-row :gutter="12">
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="关键词搜索">
                    <el-input
                      v-model="searchForm.search"
                      placeholder="学号/姓名/手机号"
                      clearable
                      prefix-icon="Search"
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="学籍状态">
                    <el-select 
                      v-model="searchForm.status" 
                      placeholder="学籍状态" 
                      clearable 
                      class="search-select"
                    >
                      <el-option label="在校" value="active" />
                      <el-option label="已毕业" value="graduated" />
                      <el-option label="休学" value="suspended" />
                      <el-option label="退学" value="dropped" />
                    </el-select>
                  </el-form-item>
                </el-col>
                
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="就业状态">
                    <el-select 
                      v-model="searchForm.employment_status" 
                      placeholder="就业状态" 
                      clearable 
                      class="search-select"
                    >
                      <el-option label="未就业" value="unemployed" />
                      <el-option label="已就业" value="employed" />
                      <el-option label="自主创业" value="self_employed" />
                      <el-option label="继续深造" value="further_study" />
                    </el-select>
                  </el-form-item>
                </el-col>
                
                <el-col :xs="24" class="search-actions-col">
                  <el-form-item class="search-actions">
                    <el-button type="primary" @click="handleSearch">
                      <el-icon><Search /></el-icon>
                      搜索
                    </el-button>
                    <el-button @click="handleReset">
                      <el-icon><RefreshLeft /></el-icon>
                      重置
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-transition>
      </div>

      <!-- 学生表格 -->
      <el-table
        :data="filteredStudentList"
        style="width: 100%"
        size="small"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="student_id" label="学号" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column label="性别" width="60">
          <template #default="{ row }">
            {{ row.gender === 'M' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column label="学籍状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="就业状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getEmploymentTagType(row.employment_status)">
              {{ getEmploymentText(row.employment_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Search, ArrowDown, RefreshLeft, Delete } from '@element-plus/icons-vue'

// 响应式数据
const studentList = ref<any[]>([])
const selectedStudents = ref<any[]>([])
const searchFormCollapsed = ref(false)

// 搜索表单
const searchForm = reactive({
  search: '',
  status: '',
  employment_status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 过滤后的学生列表
const filteredStudentList = computed(() => {
  if (!studentList.value.length) return []
  
  return studentList.value.filter(student => {
    // 关键词搜索
    if (searchForm.search) {
      const searchText = searchForm.search.toLowerCase()
      const studentIdMatch = student.student_id?.toLowerCase().includes(searchText)
      const nameMatch = student.name?.toLowerCase().includes(searchText)
      const phoneMatch = student.phone?.toLowerCase().includes(searchText)
      
      if (!studentIdMatch && !nameMatch && !phoneMatch) {
        return false
      }
    }
    
    // 学籍状态筛选
    if (searchForm.status && student.status !== searchForm.status) {
      return false
    }
    
    // 就业状态筛选
    if (searchForm.employment_status && student.employment_status !== searchForm.employment_status) {
      return false
    }
    
    return true
  })
})

// 方法
const toggleSearchForm = () => {
  searchFormCollapsed.value = !searchFormCollapsed.value
}

const handleSearch = () => {
  ElMessage.success('搜索功能已触发（实时搜索已自动生效）')
}

const handleReset = () => {
  searchForm.search = ''
  searchForm.status = ''
  searchForm.employment_status = ''
  ElMessage.info('搜索条件已重置')
}

const handleSelectionChange = (selection: any[]) => {
  selectedStudents.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
}

const handleView = (row: any) => {
  ElMessage.info(`查看学生：${row.name}`)
}

const handleEdit = (row: any) => {
  ElMessage.info(`编辑学生：${row.name}`)
}

const addMockData = () => {
  const statuses = ['active', 'graduated', 'suspended', 'dropped']
  const employmentStatuses = ['unemployed', 'employed', 'self_employed', 'further_study']
  const genders = ['M', 'F']
  const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']
  
  for (let i = 0; i < 10; i++) {
    const id = studentList.value.length + 1
    studentList.value.push({
      id,
      student_id: `2024${String(id).padStart(4, '0')}`,
      name: `${names[i % names.length]}${id}`,
      gender: genders[Math.floor(Math.random() * genders.length)],
      phone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      employment_status: employmentStatuses[Math.floor(Math.random() * employmentStatuses.length)]
    })
  }
  
  pagination.total = studentList.value.length
  ElMessage.success(`已添加 10 条模拟数据，当前总数：${studentList.value.length}`)
}

const clearData = () => {
  studentList.value = []
  pagination.total = 0
  ElMessage.info('已清空所有数据')
}

// 辅助方法
const getStatusTagType = (status: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const typeMap: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    'active': 'success',
    'graduated': 'info',
    'suspended': 'warning',
    'dropped': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    'active': '在校',
    'graduated': '已毕业',
    'suspended': '休学',
    'dropped': '退学'
  }
  return textMap[status] || status
}

const getEmploymentTagType = (status: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const typeMap: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    'unemployed': 'info',
    'employed': 'success',
    'self_employed': 'warning',
    'further_study': 'primary'
  }
  return typeMap[status] || 'info'
}

const getEmploymentText = (status: string) => {
  const textMap: Record<string, string> = {
    'unemployed': '未就业',
    'employed': '已就业',
    'self_employed': '自主创业',
    'further_study': '继续深造'
  }
  return textMap[status] || status
}
</script>

<style scoped>
/* 使用与StudentList.vue相同的样式 */
.student-list-demo {
  padding: 12px;
}

.page-card {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 8px;
  
  .el-button {
    height: 28px;
    padding: 0 12px;
    font-size: 12px;
  }
}

.search-form {
  margin-bottom: 12px;
  background: var(--bg-color-light);
  border: 1px solid var(--border-color-light);
  border-radius: 8px;
  overflow: hidden;

  .search-form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 16px;
    background: var(--fill-color-light);
    border-bottom: 1px solid var(--border-color-extra-light);

    .search-title {
      margin: 0;
      font-size: 14px;
      font-weight: 600;
      color: var(--text-color-primary);
      display: flex;
      align-items: center;
      gap: 6px;

      .el-icon {
        color: var(--color-primary);
        font-size: 16px;
      }
    }

    .search-stats {
      display: flex;
      align-items: center;
      gap: 12px;

      .result-count {
        font-size: 12px;
        color: var(--text-color-regular);
      }

      .toggle-btn {
        font-size: 12px;
        padding: 4px 8px;

        .toggle-icon {
          transition: transform 0.3s ease;
          font-size: 12px;

          &.is-collapsed {
            transform: rotate(-90deg);
          }
        }
      }
    }
  }

  .search-form-content {
    padding: 12px 16px;
  }

  .search-form-inner {
    .el-form-item {
      margin-bottom: 8px;

      :deep(.el-form-item__label) {
        font-size: 12px;
        line-height: 1.2;
        margin-bottom: 4px;
      }
    }

    .search-input,
    .search-select {
      :deep(.el-input) {
        --el-input-height: 28px;
      }
      
      :deep(.el-select) {
        --el-select-input-height: 28px;
      }
    }

    .search-actions {
      display: flex;
      gap: 8px;

      .el-button {
        height: 28px;
        padding: 0 12px;
        font-size: 12px;
      }
    }
  }
}

:deep(.el-table) {
  --el-table-row-height: 40px;
  --el-table-header-height: 36px;
  font-size: 13px;
  
  .el-button {
    height: 24px;
    padding: 0 8px;
    font-size: 12px;
  }
  
  .el-tag {
    height: 20px;
    line-height: 18px;
    font-size: 11px;
    padding: 0 6px;
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 12px;
  
  :deep(.el-pagination) {
    --el-pagination-button-height: 28px;
    --el-pagination-button-width: 28px;
    font-size: 12px;
  }
}
</style>
